package ru.tulupov.scheduledrunner.command;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * The command parser 
 * @author <a href="mailto:zhekka3@gmail.com">Eugene Tulupov</a>
 */
public class Parser {

	private final Scanner	in;

	/**
	 * The parser result
	 */
	public static class Result {
		private final String name;
		private final String[] args;

		public Result(String name, String[] args) {
			this.name = name;
			this.args = args;
		}

		/**
		 * Gets command name
		 * 
		 * @return the name
		 */
		public String getName() {
			return name;
		}

		/**
		 * Gets command arguments
		 * 
		 * @return the arguments
		 */
		public String[] getArgs() {
			return args;
		}
	}

	/**
	 * Constructs a parser
	 * 
	 * @param is
	 *            the input stream
	 */
	public Parser(InputStream is) {
		this.in = new Scanner(is);
 

	}
 
	public Result next() {
		if(!in.hasNextLine()) {
			return null;
		}
		String line = in.nextLine();

	 
		List<String> tokens = new ArrayList<String>();
		Pattern p = Pattern.compile("\\s*(\\\".*\\\"|[^\\s]+)\\s*");
		Matcher m = p.matcher(line);
		while (m.find()) {
			String s = m.group().trim();
			if (s.startsWith("\"")) {
				s = s.substring(1, s.length() - 1);
			}
			tokens.add(s);
		}

		String[] array = new String[tokens.size()];
		tokens.toArray(array);
		String name = array[0];
		String[] args = null;

		if (array.length > 1) {
			args = new String[array.length - 1];
			System.arraycopy(array, 1, args, 0, args.length);
		}
 

		return new Result(name, args);
	}
 
}
